package pl.edu.wat.erp.client.administration;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import wat.ziszcommon.clientgui.MyJPanel;
import wat.ziszcommon.clientgui.MyJTree;
import wat.ziszcommon.invoker.MethodException;
import wat.ziszcommon.invoker.UnauthorizedAccesException;
import wat.ziszcommon.transport.Module;

/**
 *
 * @author P.B. & L.G. & K.K.
 */
public class AddPluginClient extends MyJPanel {

    public AddPluginClient(String nazwa, MyJTree tree) {
        super(nazwa, tree);
        initComponents();
    // tutaj nic nie robimy - zapraszam do initClient() ;)

    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        path = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jButton2 = new javax.swing.JButton();
        send = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        name = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        name2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(AddPluginClient.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        path.setName("path"); // NOI18N
        path.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                pathKeyTyped(evt);
            }
        });

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jSeparator1.setName("jSeparator1"); // NOI18N

        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        send.setText(resourceMap.getString("send.text")); // NOI18N
        send.setEnabled(false);
        send.setName("send"); // NOI18N
        send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        name.setName("name"); // NOI18N
        name.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                nameKeyTyped(evt);
            }
        });

        jLabel3.setName("jLabel3"); // NOI18N

        name2.setName("name2"); // NOI18N
        name2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                name2KeyTyped(evt);
            }
        });

        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setName("jLabel5"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(name2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(path, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(name, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(send, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 134, Short.MAX_VALUE))
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
                    .addComponent(jButton2))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(8, 8, 8)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(name2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(send))
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addGap(102, 102, 102))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jFileChooser.setFileFilter(new ClassFileFilter());
        int retval = jFileChooser.showOpenDialog(this);
        if (retval == JFileChooser.APPROVE_OPTION) {
            path.setText(jFileChooser.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            String methodName = JOptionPane.showInputDialog("Podaj nazwę metody np. addUser");
            String methodPath = JOptionPane.showInputDialog("Podaj ścieżkę do klasy np. pl.edu.wat.methods.AddUser");
            ArrayList tmp = new ArrayList(2);
            tmp.add(methodName);
            tmp.add(methodPath);
            invokeMethod("addMethod", tmp);
        } catch (MethodException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
        } catch (UnauthorizedAccesException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void nameKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nameKeyTyped
        if (name.getText().equals("") || path.getText().equals("") || name2.getText().equals("")) {
            send.setEnabled(false);
        } else {
            send.setEnabled(true);
        }
}//GEN-LAST:event_nameKeyTyped

    private void pathKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pathKeyTyped
        if (name.getText().equals("") || path.getText().equals("") || name2.getText().equals("")) {
            send.setEnabled(false);
        } else {
            send.setEnabled(true);
        }
    }//GEN-LAST:event_pathKeyTyped

    private void sendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendActionPerformed
        String dirPath = path.getText();
        if (dirPath.endsWith(".class") && !dirPath.contains("$")) {
            File file = new File(dirPath);
            if (!file.exists()) {
                JOptionPane.showMessageDialog(this, "Plik nie istnieje!", "Błąd", JOptionPane.ERROR_MESSAGE);
                return;
            }
            FileInputStream fis = null;
            try {
                int lenght = Long.valueOf(file.length()).intValue();
                byte[] clazzBytes = new byte[lenght];
                fis = new FileInputStream(file);
                int r = fis.read(clazzBytes);
                if (r != lenght) {
                    System.out.println("BLAD PODCZAS LADOWANIA PLIKU");
                }
                Module module = new Module(name.getText(), name2.getText());
                String filename = file.getName();
                filename = filename.substring(0, filename.length() - 6);
                System.out.println("Class name:::" + filename);
                File[] linked = file.getParentFile().listFiles(new MyFilenameFilter(filename + "$"));
                module.addClazz(file.getName(), clazzBytes);
                for (File lfile : linked) {
                    System.out.println("Linked class:::" + lfile.getName());
                    int linkedLenght = Long.valueOf(lfile.length()).intValue();
                    byte[] linkedClazzBytes = new byte[linkedLenght];
                    FileInputStream linkedfis = new FileInputStream(lfile);
                    int lr = linkedfis.read(linkedClazzBytes);
                    if (lr != linkedLenght) {
                        System.out.println("BLAD PODCZAS LADOWANIA PLIKU");
                    }
                    module.addClazz(lfile.getName(), linkedClazzBytes);
                }
                String resPath = file.getParentFile().getPath() + "\\resources\\" + filename + ".properties";
                File res = new File(resPath);
                if (res.exists()) {
                    System.out.println("RESOURCE:::" + resPath);
                    int resLenght = Long.valueOf(res.length()).intValue();
                    byte[] resClazzBytes = new byte[resLenght];
                    FileInputStream resfis = new FileInputStream(res);
                    int rr = resfis.read(resClazzBytes);
                    if (rr != resLenght) {
                        System.out.println("BLAD PODCZAS LADOWANIA PLIKU");
                    }
                    module.setResource(resClazzBytes);
                    ArrayList tmp = new ArrayList(1);
                    tmp.add(module);
                    invokeMethod("addModule", tmp);

                } else {
                    System.out.println("BRAK PLIKU RESOURCE!!!");
                }
                System.out.println(path + " (" + name + ") OK.");
            } catch (MethodException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
            } catch (UnauthorizedAccesException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
            } finally {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(AddPluginClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        } else {
            JOptionPane.showMessageDialog(this, "Wybrano nieprawidłowy plik!", "Błąd", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_sendActionPerformed

    private void name2KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_name2KeyTyped
        if (name.getText().equals("") || path.getText().equals("") || name2.getText().equals("")) {
            send.setEnabled(false);
        } else {
            send.setEnabled(true);
        }
    }//GEN-LAST:event_name2KeyTyped

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField name;
    private javax.swing.JTextField name2;
    private javax.swing.JTextField path;
    private javax.swing.JButton send;
    // End of variables declaration//GEN-END:variables

    @Override
    public void initClient() {
        System.out.println("Inicjalizacja modulu dodawania nowych modulow...");


    }

    class ClassFileFilter extends FileFilter {

        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
            String path = f.getName().toLowerCase();
            if (path.endsWith(".class") && !path.contains("$")) {
                return true;
            }
            return false;
        }

        public String getDescription() {
            return ".class files";
        }
    }

    class MyFilenameFilter implements FilenameFilter {

        private String prefix;

        public MyFilenameFilter(String prefix) {
            this.prefix = prefix;
        }

        public boolean accept(File dir, String name) {
            if (name.startsWith(prefix)) {
                return true;
            } else {
                return false;
            }
        }
    }
}
